package com.glasses.business.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.glasses.business.R;
import com.glasses.business.adapter.AddrAdapter;
import com.glasses.business.adapter.HomeAdapter;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.AppBaseFragment;
import com.glasses.business.base.MyBaseAdapter;
import com.glasses.business.entity.Address;
import com.glasses.business.entity.GlassDetail;
import com.glasses.business.event.BussEvent;
import com.glasses.business.http.NetUtils;
import com.glasses.business.inter.OnItemClick;
import com.glasses.business.utils.Tools;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.neiquan.applibrary.wight.RefreshLayout;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.ToastUtil;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/8
 * Version：1.0
 */

public class AddrFragment extends AppBaseFragment implements RefreshLayout.RetryListener, XRecyclerView.LoadingListener {
    @InjectView(R.id.recyclerview)
    XRecyclerView mRecyclerview;
    @InjectView(R.id.refesh_ly)
    RefreshLayout mRefeshLy;
    @InjectView(R.id.addrNew)
    TextView addrNew;
    private AddrAdapter adapter;
    private int pageNum = 0;
    private int PAEG_SIZE = 10;
    private List<Address> list;

    @Override
    public int getRootViewId() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return R.layout.fragment_addr;
    }


    public void onEventMainThread(BussEvent event) {
        if (event.getState() == BussEvent.Save_Addr) {
            onRefresh();
        }
    }

    @Override
    public void setViews() {
        setTitleTv("地址管理");
        adapter = new AddrAdapter(getActivity(), null);
        mRecyclerview.setAdapter(adapter);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setOrientation(StaggeredGridLayoutManager.VERTICAL);
        mRecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerview.setArrowImageView(R.mipmap.iconfont_downgrey);
        mRecyclerview.setHasFixedSize(true);
        mRecyclerview.setLayoutManager(layoutManager);
        mRefeshLy.setRetryListener(this);

        mRecyclerview.setLoadingListener(this);
        mRecyclerview.setLoadingMoreEnabled(false);
        mRecyclerview.setPullRefreshEnabled(true);
        adapter.setOnItemClick(new OnItemClick() {
            @Override
            public void onItemClick(int type, Object obj) {
                final Address address = (Address) obj;
                switch (type) {
                    case 0:
                        new AlertDialog.Builder(getActivity()).setMessage("确认删除收货地址？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        dialogInterface.dismiss();
                                        Tools.showDialog(getActivity());
                                        NetUtils.getInstance().delAddress(address.getId(), new NetCallBack() {
                                            @Override
                                            public void onSuccess(String response, String mssage, ResultModel model) {
                                                Tools.dismissWaitDialog();
                                                ToastUtil.shortShowToast(mssage);
                                                onRefresh();
                                            }

                                            @Override
                                            public void onFail(boolean dataError, int errorCode, String mssage) {
                                                Tools.dismissWaitDialog();
                                                ToastUtil.shortShowToast(mssage);
                                            }
                                        }, null);
                                    }
                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).create().show();
                        break;
                    case 1:
                        Bundle args = new Bundle();
                        args.putSerializable("address", address);
                        open(new AddrEditFragment(), args);
                        break;
                    case 2:
                        Tools.showDialog(getActivity());
                        NetUtils.getInstance().defaultAddr(address.getId(), new NetCallBack() {
                            @Override
                            public void onSuccess(String response, String mssage, ResultModel model) {
                                Tools.dismissWaitDialog();
                                ToastUtil.shortShowToast(mssage);
                                onRefresh();
                            }

                            @Override
                            public void onFail(boolean dataError, int errorCode, String mssage) {
                                Tools.dismissWaitDialog();
                                ToastUtil.shortShowToast(mssage);
                            }
                        }, null);
                        break;
                    case 3:
                        BussEvent event = new BussEvent(BussEvent.Address);
                        event.setMessage(address);
                        EventBus.getDefault().post(event);
                        MyApplication.getInstance().manager.onBackPressed();
                        break;
                }
            }
        });
    }

    @Override
    public void initData() {
        loadDatas(true);
    }

    private void loadDatas(final boolean isRefush) {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().addressList(pageNum, PAEG_SIZE, new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                mRecyclerview.loadMoreComplete();
                mRecyclerview.refreshComplete();
                mRefeshLy.hideAll();
                list = (List<Address>) model.getModelList();
                if (isRefush) {
                    adapter.clear();
                }
                adapter.append(list);
                if (list == null || list.size() < 10) {
                    if (isRefush && (list == null || list.size() == 0)) {
//                        mRefeshLy.showEmptyView();
                        mRefeshLy.showFailView();
                    }
                    mRecyclerview.setLoadingMoreEnabled(false);
                } else {
                    mRecyclerview.setLoadingMoreEnabled(true);
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                //                mRefeshLy.hideAll();
                mRefeshLy.showFailView();
                mRecyclerview.loadMoreComplete();
                mRecyclerview.refreshComplete();
            }
        }, Address.class);
    }

    @Override
    public boolean mainTabShow() {
        return false;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @OnClick(R.id.addrNew)
    public void onClick() {
        open(new AddrEditFragment());
    }

    @Override
    public void onRetryClick() {
        pageNum = 0;
        loadDatas(true);
    }

    @Override
    public void onRefresh() {
        pageNum = 0;
        loadDatas(true);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        loadDatas(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
